package com.xjoyt.pay.operater.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.operater.auth.params.RolePageParam;
import com.xjoyt.pay.operater.auth.po.Role;
import com.xjoyt.pay.operater.dao.RoleRepositoryCustom;
import com.xjoyt.pay.operater.repository.RoleRepository;

public class RoleRepositoryImpl extends AbstractDao implements RoleRepositoryCustom {

	@Autowired
	private RoleRepository repository;

	@Override
	public PageResult<Role> loadPage(PageParam<RolePageParam> param) {
		Pageable pageable = getPageable(param);
		Specification<Role> spec = getSpecification(param.query);
		Page<Role> pageReuslt = repository.findAll(spec, pageable);
		return new PageResult<>(pageReuslt.getTotalElements(), pageReuslt.getContent());
	}

	private Specification<Role> getSpecification(RolePageParam param) {
		Specification<Role> spec = (root, query, cb) -> {
			List<Predicate> list = new ArrayList<>();
			if (param == null) {
				return null;
			}
			if (StringUtils.isNotBlank(param.companyId))
				list.add(cb.equal(root.get("companyId"), param.companyId));

			if (StringUtils.isNotBlank(param.query)) {
				for (String string : param.query.split(" ")) {
					if (StringUtils.isBlank(string))
						continue;
					String like = "%" + string + "%";
					list.add(cb.or(cb.like(root.get("name"), like), cb.like(root.get("account"), like),
							cb.like(root.get("phone"), like), cb.like(root.get("email"), like),
							cb.like(root.get("remark"), like)));
				}
			}

			if (param.enabled != null) {
				if (param.enabled)
					list.add(cb.equal(root.get("enabled"), param.enabled));
				else
					list.add(cb.or(cb.equal(root.get("enabled"), false), cb.isNull(root.get("enabled"))));
			}
			if (CollectionUtils.isNotEmpty(list))
				query.where(cb.and(list.toArray(new Predicate[list.size()])));

			return null;
		};
		return spec;
	}

	@Override
	public List<Role> findAll(RolePageParam param) {
		Specification<Role> spec = getSpecification(param);
		return repository.findAll(spec);
	}
}
